#!/bin/sh

set -ue

PORT=${1-8250}

OUT_DIR=/tmp/tidb_binlog_test

# kill pump, util no pump process is running
while :
do
        pump_num=`ps aux > temp && grep "pump -log-file ${OUT_DIR}/pump_${PORT}.log" temp | wc -l && rm temp`
        if [ $pump_num -ne 0 ]; then
                echo "try pause pump"
                binlogctl -ssl-ca $OUT_DIR/cert/ca.pem \
		            -ssl-cert $OUT_DIR/cert/client.pem \
		            -ssl-key $OUT_DIR/cert/client.key \
                    -pd-urls https://127.0.0.1:2379 -cmd pause-pump -node-id pump:$PORT || true
                sleep 1
        else
                break
        fi
done

echo "[$(date)] <<<<<< RUNNING pump  >>>>>>" >> "$OUT_DIR/pump_$PORT.log"

cat - > "$OUT_DIR/pump-config.toml" <<EOF
[security]
ssl-ca = "$OUT_DIR/cert/ca.pem"
ssl-cert = "$OUT_DIR/cert/pump.pem"
ssl-key = "$OUT_DIR/cert/pump.key"
cert-allowed-cn = ["binlog"]
EOF

BINLOG_TEST=1 pump -log-file $OUT_DIR/pump_$PORT.log --addr=0.0.0.0:$PORT \
        --advertise-addr=127.0.0.1:$PORT \
        -config "$OUT_DIR/pump-config.toml" \
        --pd-urls=https://127.0.0.1:2379 \
        --data-dir=$OUT_DIR/pump_$PORT \
        --node-id=pump:$PORT >> $OUT_DIR/pump_$PORT.log 2>&1
